/* Init method */
function init() {	
	// Calculate total amount for cart
	calculateTotalCart();	
}

/* Browse to URL */
function doNav(sUrl)
{
	document.location.href = sUrl;
}

/* sort the products list */
function sortList(order, page, amount) {
	if (amount == null) {
		amount = document.getElementById("pppSelector").value;
	}
	var xmlHttp = null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlHttp == false) {
		alert("Error: no AJAX support in your browser");
		return;
	}
	var url = "processProductsController.html?ord=" + order + "&pag=" + page + "&amo=" + amount;

	if(!callInProgress(xmlHttp)) {
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange= function() {
			if (xmlHttp.readyState==4) {
				document.getElementById("products").innerHTML = xmlHttp.responseText;
			}
		}; 
		xmlHttp.send(null);
	}
}

/* Add the "cursor" pointer to a clickable row */
function changeClass(id) {
	id.className='cursorPointer';  
}

/* Toggle order amount field */
function toggleOrderAmountField(p_id, evenRow) {
	if(evenRow) {
		document.getElementById("amountField"+p_id).style.backgroundColor = "#ff9999";
	}
	document.getElementById("amountField"+p_id).innerHTML = "<input type=\"text\" id=\"amount"+p_id+"\" onchange=\"orderItem("+p_id+");\" size=\"4\" maxlength=\"2\" /> stuks";
}

/* Order an item */
function orderItem(p_id) {
	// Get amount of ordered products
	var amount = document.getElementById("amount"+p_id).value;
	
	var xmlHttp = null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlHttp == false) {
		alert("Error: no AJAX support in your browser");
		return;
	}
	
	var url="processCartController.html?pId=" + p_id + "&amo=" + amount;
	if(!callInProgress(xmlHttp)) {
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				// Add visible data to cart
				addToCart(p_id, amount);
			}
		}; 
		xmlHttp.send(null);
	}
}

/* Remove an item */
function removeItem(p_id) {
	var xmlHttp = null;
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp = new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlHttp == false) {
		alert("Error: no AJAX support in your browser");
		return;
	}
	
	var url="processCartController.html?rPd=" + p_id;

	if(!callInProgress(xmlHttp)) {
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4) {
				// Visually remove item
				removeFromCart(p_id);
				
				// Recalculate total amount in cart
				calculateTotalCart();
				
				// Reset, if available, order fields
				if(document.getElementById("amount"+p_id) != null) {
					document.getElementById("amount"+p_id).value = "";
				}
			}
		}; 
		xmlHttp.send(null);
	}
}

/* Visually remove item from cart */
function removeFromCart(p_id) {
	var oNodeToRemove = document.getElementById("item"+p_id);
	oNodeToRemove.parentNode.removeChild(oNodeToRemove);
}

/* Visually add item to cart */
function addToCart(p_id, amount) {
	if(document.getElementById("item"+p_id) != null) {
		removeFromCart(p_id);
	}

	var currentCart = document.getElementById("shoppingCartContent").innerHTML;
	var product 	= document.getElementById("product" + p_id).innerHTML;
	var workPrice 	= document.getElementById("price" + p_id).innerHTML;
	workPrice		= workPrice.substr(2,workPrice.length);
	workPrice		= workPrice.replace(/,/, ".");
	workPrice		= workPrice * amount;
	
	workPrice		= Math.round(workPrice*100)/100;
	var printPrice 	= workPrice.toString();
	
	if(printPrice.indexOf(".") != -1) {
		var split 		= printPrice.split(".");
		if(split[1].length == 1) {
			split[1] 	+= "0";
		}
		printPrice 		= split.join(",");
	} else {
		printPrice += ",00";
	}
	
	var data 		= "<tr id=\"item"+p_id+"\">" +
						"<td>("+amount+"x)"+product+"</td>" +
						"<td class=\"itemPrice\">"+printPrice+"</td>" +
						"<td><a href=\"#\" onclick=\"removeItem("+p_id+");\">X</a></td>" +
					  "</tr>";
	var newData;
	
	if(currentCart != "" && currentCart != null) {
		newData = currentCart + data;
	} else {
		newData = data;
	}
	
	document.getElementById("shoppingCartContent").innerHTML = newData;
	
	calculateTotalCart();
}

/* Calculate total amount in cart */
function calculateTotalCart() {
	var xpathResult = document.evaluate( "//td[@class=\"itemPrice\"]", document, null, XPathResult.ANY_TYPE, null);
	var totalPrice = 0;
	if(xpathResult != null) {
		try {
			  var thisNode = xpathResult.iterateNext();
			  
			  while (thisNode) {
				  var currentPrice = thisNode.textContent;
				  currentPrice = currentPrice.replace(/,/, ".");
				  currentPrice = parseFloat(currentPrice);
				  
				  totalPrice = totalPrice + currentPrice;
				  
				  thisNode = xpathResult.iterateNext();
			  }	
			}
		catch (e) {
		  dump( 'Error: Document tree modified during iteration ' + e );
		}
	
		totalPrice 		= Math.round(totalPrice*100)/100;
		totalPrice 		= totalPrice.toString();
		
		if(totalPrice != 0) {
			if(totalPrice.indexOf(".") != -1) {
				var split 		= totalPrice.split(".");
				if(split[1].length == 1) {
					split[1] 	+= "0";
				}
				totalPrice 		= split.join(",");
			} else {
				totalPrice += ",00";
			}
		} else {
			totalPrice = "0,00";
		}
		
		document.getElementById("totalPriceCart").innerHTML = totalPrice;
	}
}

/* Validate order form */
function validateOrderForm() {
	var name = document.getElementById('name').value;
	var address = document.getElementById('address').value;
	var city = document.getElementById('city').value;
	var phone = document.getElementById('phone').value;
	var errors = 0;
	var error = 'Let op, de bestelling kan niet worden verwerkt. Controleer de volgende velden:\n\n'; 	if(name != '') {
	} else {
		errors++;
		error += "- Naam\n";
	}
	
	if(address != '') {
	} else {
		errors++;
		error += "- Straat + nr\n";
	}
	
	var matches = phone.match("^[0-9]{10}|[0-9]{0,4}\-[0-9]{6,8}$");
	if(matches == null) {
		errors++;
		error += "- Het telefoonnummer is niet correct.";
	} else {
	} 	/* Prompt on errors or else continue on valid form. */
	if(errors > 0) {
		alert(error);
		return false;
	} else {
		doNav('orderCartController.html?nam='+name+"&adr="+address+"&tow="+city+"&pho="+phone);
	}
}

/* Check the readyState and return true when there is a call in progress */
function callInProgress(xmlHttp) {
	if (xmlHttp) {
		switch (xmlHttp.readyState) {
			case 1:
			case 2:
			case 3:	return true;
		}
	} 
	return false;
}